﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Windows.Forms;
using WinForm.NET4.Sample.CustomControl.Enum;
 

namespace WinForm.NET4.Sample.CustomControl
{
    public partial class AwesomeIcon : Control
    {
        public AwesomeIcon()
        {
            InitializeComponent();

            if (ImageFont.Families.Length == 0)
            {
                var curNamespace = this.GetType().Namespace;

                Stream fontStream = this.GetType().Assembly.GetManifestResourceStream(curNamespace + ".Font.fontawesome.ttf");

                byte[] fontdata = new byte[fontStream.Length];

                fontStream.Read(fontdata, 0, (int)fontStream.Length);

                fontStream.Close();
                unsafe
                {
                    fixed (byte* pFontData = fontdata)
                    {
                        ImageFont.AddMemoryFont((System.IntPtr)pFontData, fontdata.Length);
                    }
                }
            }
       
            if (ImageFont.Families.Length == 0)
            {
                return;
            }
            else
            {
                iconfont = new Font(ImageFont.Families[0], Font.Size, FontStyle.Bold, Font.Unit);
            }
        }

        private PrivateFontCollection ImageFont = new PrivateFontCollection();

        private Font iconfont;
        private SizeF FontSize = new SizeF();
        private SolidBrush foreSolidBrush = new SolidBrush(DefaultForeColor);

        private string FontValue = "";

        private AwesomeValues _Value = AwesomeValues.None;

        public AwesomeValues Value
        {
            get => _Value;
            set
            {
                _Value = value;

                //if (value == AwesomeValues.None) return;

                FontValue = char.ConvertFromUtf32((int)_Value);
                Invalidate();
            }
        }
    
 

        ~AwesomeIcon()
        {
            foreSolidBrush?.Dispose(); iconfont?.Dispose();
        }

        private void AwesomeIcon_Paint(object sender, PaintEventArgs e)
        {
            if (ImageFont.Families.Length < 1) return;
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;  //使绘图质量最高，即消除锯齿
            e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
            e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;

            foreSolidBrush.Color = ForeColor;
            iconfont = new Font(ImageFont.Families[0], Font.Size, FontStyle.Bold, Font.Unit);
            FontSize = e.Graphics.MeasureString(FontValue, iconfont);
            e.Graphics.DrawString(FontValue, iconfont, foreSolidBrush, (Width - FontSize.Width) / 2, (Height - FontSize.Height) / 2);
        }

     
    }
}
